package com.zwj.service.impl;

import com.zwj.dto.Result;
import com.zwj.enums.ErrorEnum;
import com.zwj.interceptor.BizException;
import com.zwj.service.FileService;
import com.zwj.utils.FileUtils;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;

@Service
public class FileServiceImpl implements FileService {
    @Override
    public Result upload(MultipartFile file) {
        try {
            if(file.isEmpty()){
                return Result.error().message("上传文件为空");
            }
            String fileName = file.getOriginalFilename();
            String[] fn = fileName.split("\\.");
            if(fn.length<2){
                return Result.error().message("文件名格式不符合");
            }
            String fileExtension = fn[fn.length-1];
            if (!FileUtils.isFileExtension(fileExtension)) return Result.error().message("上传文件失败，含有不被接受的文件名");
            String os = System.getProperty("os.name");
            File fileRealPath = new File(FileUtils.mkdirs(new ApplicationHome(getClass())));   //文件存放地址
            String name = null;
            File resultPath =null;
            int i;
            for (i = 0; i < 3; i += 1) {
                //获取文件名称
                name = FileUtils.getFileName();
                //创建文件存放地址
                resultPath = new File(fileRealPath+"/"+name+"."+fileExtension);
                if (!resultPath.exists()){
                    break;
                }
            }
            if (i >= 3) {
                return Result.error().message("上传文件失败，失败原因生成文件名失败");
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            file.transferTo(resultPath);
            return Result.ok().data(name+"."+fileExtension);
        }catch (Exception e){
            return Result.error().message("上传文件失败");
        }
    }
    @Override
    public ResponseEntity<Resource> downloadFile(String fileName, HttpServletRequest request) throws UnsupportedEncodingException {
        if (fileName == null || fileName.equals("")) {
            throw new BizException(ErrorEnum.BODY_NOT_MATCH.getResultCode(),"文件名为空");
        }
        String dirPath = FileUtils.mkdirs(new ApplicationHome(getClass()));
        Path filePath = Paths.get(dirPath).toAbsolutePath().normalize();
        Path path = filePath.resolve(fileName).normalize();
        Resource resource = null;
        try {
            resource = new UrlResource(path.toUri());
            if (!resource.exists()) {
                throw new BizException(ErrorEnum.BODY_NOT_MATCH.getResultCode(),"文件找不到");
            }
        } catch (MalformedURLException e) {
            throw new BizException(ErrorEnum.BODY_NOT_MATCH.getResultCode(),"文件错误");
        }
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException e) {
            throw new BizException(ErrorEnum.BODY_NOT_MATCH.getResultCode(),"无法获取文件格式");
        }
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + new String(resource.getFilename().getBytes("UTF-8"),"iso-8859-1")  + "\"")
                .body(resource);
    }
}
